package com.boe.hbd.client.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;

import com.boe.hbd.client.Constants;
import com.boe.hbd.client.R;
import com.boe.hbd.client.domain.Landscape;
import com.boe.hbd.client.persistence.EntityManager;
import com.boe.hbd.client.service.ServiceManager;

public class LandscapeIntroductionActivity extends Activity implements OnClickListener {
	private EntityManager entityManager;
	private Landscape landscape = null ;
	
	public void onCreate(Bundle theInstance) {
		super.onCreate(theInstance);
		setContentView(R.layout.landscape_introduction_activity);
		findViewById(R.id.saveLandscapeImageView).setOnClickListener(this);
		findViewById(R.id.cancelLandscapeImageView).setOnClickListener(this);
		entityManager = ServiceManager.getInstance(null).getService(EntityManager.class);
		
		Long landscapeId = getIntent().getExtras().getLong(Constants.KEY_LANDSCAPE_ID);
		
		if (landscapeId != null) {
			landscape = entityManager.getById(Landscape.class, landscapeId);
			if (landscape != null) {
				((EditText) findViewById(R.id.landscape_name)).setText(landscape.getName());
				((EditText) findViewById(R.id.landscape_description)).setText(landscape.getDescription());
			}
		}
	}

	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.cancelLandscapeImageView: {
				setResult(RESULT_CANCELED);
			}
			break;
			case R.id.saveLandscapeImageView: {
				Landscape createdLandscape = save();
				Intent intent = new Intent(this, LandscapeIntroductionActivity.class);
				Bundle bundle = new Bundle();
				bundle.putLong(Constants.KEY_LANDSCAPE_ID, createdLandscape.getId());
				intent.putExtras(bundle);
				if (getParent() == null) {
				    setResult(Activity.RESULT_OK, intent);
				} else {
				    getParent().setResult(Activity.RESULT_OK, intent);
				} 
			}
			break;
		}
		finish();
	}

	private Landscape save() {
		String name = ((EditText) findViewById(R.id.landscape_name)).getText().toString();
		String description = ((EditText) findViewById(R.id.landscape_description)).getText().toString();
		if ( landscape == null) {
			double latitude = getIntent().getExtras().getDouble(Constants.KEY_LATITUDE);
			double longtitude = getIntent().getExtras().getDouble(Constants.KEY_LONGTITUDE);
			landscape = new Landscape(latitude, longtitude, name, description);
			landscape = entityManager.create(landscape);
		} else {
			landscape.setName(name);
			landscape.setDescription(description);
			landscape = entityManager.update(landscape);
		}
		return landscape;
	}
}
